__author__ = 'cq'

import socket
import sys
import getopt
import fileinput


def main(argv):

    inputfile = 'not defined'
    server_addr = 'not defined'
    verbose = False
    try:
        opts, args = getopt.getopt(argv, "hvi:s:", ["ifile=", "server="])
    except getopt.GetoptError:
        print 'textdumper.py -i <inputfile> -s <server ip:port> <-v>'
        sys.exit(2)

    for opt, arg in opts:
        if opt == '-h':
            print 'textdumper.py -i <inputfile> -s <server ip:port> <-v>'
            sys.exit()
        elif opt in ("-i", "--ifile"):
            inputfile = arg
        elif opt in ("-s", "--server"):
            server_addr = arg
        elif opt in ("-v", "--verbose"):
            verbose = True

    s_conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    server = server_addr.split(":")[0]
    port = int(server_addr.split(":")[1])
    try:
        if verbose:
            print 'Connecting to ' + server + ' ' + str(port)

        s_conn.connect((server, port))
        for line in fileinput.input([inputfile]):
            s_conn.send(line)
            if verbose:
                print line

        if verbose:
            print 'Disconnecting to ' + server + ' ' + str(port)
        s_conn.close()
        if verbose:
            print 'Disconnected.'
    except socket.gaierror:
        print 'Error: ' + socket.gaierror.message


if __name__ == "__main__":
    main(sys.argv[1:])
